package com.xiaowu.commons.scan;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.xiaowu.commons.utils.CommonUtils;
import com.xiaowu.web.model.Resource;
import com.xiaowu.web.model.Syslog;
import com.xiaowu.web.service.ISysLogService;
import com.xiaowu.web.vo.ActiveUser;

/**
 * @description：AOP 日志
 */
@Aspect
@Component
public class SysLogAspect {
	
	@Autowired
	private EhCacheManager cacheManager;
	
	@Autowired
	private ISysLogService sysLogService;

    @Around("within(@org.springframework.stereotype.Controller *)")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {

        String strMethodName = point.getSignature().getName();
        String strClassName = point.getTarget().getClass().getName();
        Object[] params = point.getArgs();
        StringBuffer bfParams = new StringBuffer();
        Enumeration<String> paraNames = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (params != null && params.length > 0) {
            paraNames = request.getParameterNames();
            String key;
            String value;
            while (paraNames.hasMoreElements()) {
                key = paraNames.nextElement();
                value = request.getParameter(key);
                bfParams.append(key).append("=").append(value).append("&");
            }
            if (StringUtils.isBlank(bfParams)) {
                bfParams.append(request.getQueryString());
            }
        }

     

        if(isWriteLog(request.getRequestURI())){
        	   String strMessage = String
                       .format("[类名]:%s,[方法]:%s,[参数]:%s", strClassName, strMethodName, bfParams.toString());
               //System.out.println(strMessage);
               String address = request.getRequestURI().replaceAll(request.getContextPath(), "");
               Map<String,String> urlMap = (Map<String,String>)cacheManager.getCache("shiroCache").get("urlList");
               if((null!=urlMap && urlMap.size()>0)||address.contains("login")){
               		//System.out.println(urlMap.get(address));
               		Syslog syslog = new Syslog();
               		syslog.setClientIp(CommonUtils.getIpAddr(request));
               		syslog.setCreateTime(new Date());
               		if(null!=urlMap) syslog.setRoleName(urlMap.get(address));
               		String name =getMapMenuName(address);
               		if(null!=name) syslog.setRoleName(name);
               		syslog.setOptContent(strMessage);
               		System.out.println("------------------------------------------------------------"+strMessage.length()+"------------------------------------------------------------------");
               		System.out.println(strMessage);
               		System.out.println("------------------------------------------------------------------------------------------------------------------------------");
               		if(strMessage.length()>1000){
               			syslog.setOptContent(strMessage.substring(0,1000));
               		}
               		
               	  	Subject subject = SecurityUtils.getSubject();  
               	  	if(null!=subject&&null!=subject.getPrincipals()){
               	  		ActiveUser activeUser = (ActiveUser)subject.getPrincipals().getPrimaryPrincipal();
               	  		syslog.setLoginName(activeUser.getUserloginname());
               	  	}
               	  	
               		sysLogService.addSysLog(syslog);
               }
              
        }
        
        return point.proceed();
    }
    

    private boolean isWriteLog(String method) {
    	//登录(login)、退出(exit)、首页(home)
        String[] pattern = {"login", "exit", "home","Add", "Update", "Delete", "Export","Data","Detailed","Operation"};
        for (String s : pattern) {
            if (method.indexOf(s) > -1) {
                return true;
            }
        }
        return false;
    }
    
    public String getMapMenuName(String name){
    	if(name.contains("/login")) return "登录";
    	if(name.contains("/exit")) return "退出";
    	if(name.contains("/home")) return "首页";
    	return null;
    }
    
}
